Implementing Distributed Caching with Redis in ASP.NET
TLDR
- For Windows environments, it is recommended to use WSL 2 or Docker to install Redis; using the legacy installer archived by Microsoft is not recommended.
- For development environments, Memurai can be used as a Windows-compatible alternative to Redis.
- When installing Redis via Docker, if external connections fail, you need to adjust the
bindandprotected-modesettings inredis.conf. - For ASP.NET Core, it is recommended to use the
IDistributedCacheinterface to implement distributed caching; if you are in a single-server environment,IMemoryCacheoffers better performance. - For ASP.NET Framework, you can use the
StackExchange.Redispackage to access Redis directly viaConnectionMultiplexer.
Installing Redis on Windows
Redis does not natively support Windows. If you need to develop or test in a Windows environment, the following approaches are recommended:
- WSL 2: The officially recommended solution, offering the best performance and stability.
- Memurai: A Redis-compatible Windows port, suitable for development and testing environments.
- Docker: Installed via the official image, suitable for containerized deployments.
Notes on Installing via Docker
When you might encounter issues: When running Redis inside a Docker container, but external applications cannot connect.
- If you need custom configurations, please mount the
redis.conffile. - If a
Connection refusederror occurs, please check theredis.confsettings:- Comment out
bind 127.0.0.1 -::1to allow external connections. - Change
protected-mode yestoprotected-mode no.
- Comment out
Example docker-compose.yml configuration:
version: '3.8'
services:
Redis-Server:
image: redis:7
container_name: Redis-Server
ports:
- 6379:6379
volumes:
- .\Volumes\Data:/data
- .\Volumes\Config:/usr/local/etc/redis
command: redis-server /usr/local/etc/redis/redis.conf
restart: alwaysUsing Caching in ASP.NET Core
MemoryCache (In-Memory Caching)
When you might encounter issues: When the application is deployed on a single server and does not need to share state across machines.
- Use the
IMemoryCacheinterface. - Strategy selection:
- Absolute: Absolute expiration time; the item is removed once the time expires.
- Sliding: Sliding expiration time; the expiration time is extended if the item is accessed continuously.
IDistributedCache (Distributed Caching)
When you might encounter issues: When the application is deployed on multiple servers and needs to share cached data.
- Use the
Microsoft.Extensions.Caching.StackExchangeRedispackage. - Register the service:
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "SampleInstance";
});WARNING
If there is only one App Server, it is recommended to prioritize IMemoryCache. This is because IMemoryCache reads from local memory, which is faster than remote Redis, and the API supports a richer set of data types, whereas IDistributedCache natively only supports string.
Using Redis in ASP.NET Framework
When you might encounter issues: When you need to integrate Redis into legacy .NET Framework projects.
- Use the
StackExchange.Redispackage. - It is recommended to use the Singleton pattern to manage
ConnectionMultiplexerto maintain connection stability.
public sealed class RedisConnection {
private static readonly Lazy<RedisConnection> lazy = new Lazy<RedisConnection>(() => new RedisConnection());
private RedisConnection() {
ConnectionMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
}
public static RedisConnection Instance => lazy.Value;
public ConnectionMultiplexer ConnectionMultiplexer { get; }
}Usage example:
IDatabase db = RedisConnection.Instance.ConnectionMultiplexer.GetDatabase(0);
string cachedValue = await db.StringGetAsync("CacheKey");Change Log
- 2022-11-02 Initial document creation.